<template>
  <el-card>
    <el-form ref="form" label-width="80px" :inline="true" class="form">
      <el-form-item label="职位搜索">
        <el-input v-model="keyWord" placeholder="请输入搜索职位"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="search"
          :disabled="keyWord == '' ? true : false"
        >
          搜索
        </el-button>
        <el-button :plain="true" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 5px 0">
    <el-button
      size="small"
      type="primary"
      icon="Plus"
      @click="addRole"
      v-has="`btn.Role.addbtn.Role.assgin`"
    >
      添加职位
    </el-button>
    <el-table
      border
      :data="allRoleList"
      style="width: 100%; margin: 10px 0"
      label-width="80px"
    >
      <el-table-column
        align="center"
        type="index"
        label="序号"
        width="80px"
      ></el-table-column>
      <el-table-column align="center" prop="id" label="ID"></el-table-column>
      <el-table-column
        align="center"
        prop="roleName"
        label="职位名称"
        width="width"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        prop="createTime"
        label="创建时间"
        width="width"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        prop="updateTime"
        label="更新时间"
        width="width"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column align="center" label="操作" width="280px">
        <!-- row代表已有的职位对象 -->
        <template #="{ row }">
          <el-button
            type="primary"
            size="small"
            title="分配权限"
            icon="user"
            @click="setPermisstion(row)"
            v-has="`btn.Role.assgin`"
          >
            分配权限
          </el-button>
          <el-button
            type="primary"
            size="small"
            title="编辑"
            icon="Edit"
            @click="updateRole(row)"
            v-has="`btn.Role.update`"
          >
            编辑
          </el-button>
          <el-popconfirm
            class="box-item"
            :title="`确定要删除${row.roleName}么?`"
            placement="top-start"
            @confirm="removeRole(row)"
            @cancel="removeCancel"
            width="200px"
          >
            <template #reference>
              <el-button
                type="primary"
                size="small"
                title="删除"
                icon="Delete"
                v-has="`btn.Role.remove`"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin: 10px 0"
      v-model:current-page="pageInfo.pageNo"
      v-model:page-size="pageInfo.limit"
      :page-sizes="[3, 5, 7, 10]"
      size="small"
      :background="true"
      layout=" prev, pager, next, jumper,->,sizes,total,"
      :total="pageInfo.total"
      @size-change="handleSizeChange"
      @current-change="getHasRole"
    />
  </el-card>
  <!-- 添加职位于更新职位对话框 -->
  <el-Dialog
    v-model="dialogVisite"
    width="500px"
    :title="roleParams.id ? '编辑职位' : '添加职位'"
  >
    <el-form
      ref="formRef"
      label-width="80px"
      :rules="rules"
      :model="roleParams"
    >
      <el-form-item label="职位名称" prop="roleName">
        <el-input
          v-model="roleParams.roleName"
          placeholder="请你输入职位名称"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :plain="true" @click="cancel">取消</el-button>
      <el-button type="primary" @click="saveRole">确定</el-button>
    </template>
  </el-Dialog>
  <!-- 抽屉组件 用于分配职位权限于按钮权限 -->
  <el-drawer v-model="drawer" direction="rtl" size="400">
    <!-- 头部标题 -->
    <template #header>
      <h4>分配菜单权限与按钮权限</h4>
    </template>
    <template #default>
      <el-form ref="formRef" label-width="80px">
        <!--树形控件菜单数据 -->
        <el-tree
          ref="tree"
          style="max-width: 600px"
          :data="menuListArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="checkedArr"
          :props="defaultProps"
        />
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqRemove,
  reqAllMenuList,
  reqSetPermission,
} from '@/api/acl/role/index'
import {
  RoleResponseData,
  Records,
  RoleData,
  MenuResponseData,
  MenuList,
} from '@/api/acl/role/type'
import { reactive, ref, onMounted, nextTick } from 'vue'
import useLayoutSettingStore from '@/store/modules/setting'
import { ElMessage } from 'element-plus'
//获取模板setting仓库
let settingStore = useLayoutSettingStore()
let pageInfo = reactive({
  pageNo: 1,
  limit: 5,
  total: 0,
})
let keyWord = ref<string>('')
//获取添加职位表单实例对象
let formRef = ref<any>()
//存储全部已有的职位
let allRoleList = ref<Records>([])
//添加对话框和更新对话框显示与隐藏
let dialogVisite = ref<boolean>(false)
let roleParams = reactive<RoleData>({
  roleName: '',
})
let drawer = ref<boolean>(false)
//树形控件数据格式
const defaultProps = {
  children: 'children',
  label: 'name',
}
const menuListArr = ref<MenuList>([])
//保存勾选的子节点数组
let checkedArr = ref<any>([])
let tree = ref<any>()
//@ts-ignore
const validatorRoleName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('职位名称长度至少2位!'))
  }
}
//自定义表单校验规则
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
//改变每页条数
const handleSizeChange = () => {
  //   pageInfo.limit = value
  getHasRole()
}
onMounted(() => {
  //获取职位接口
  getHasRole()
})
const getHasRole = async (pager = 1) => {
  //修改当前页码
  pageInfo.pageNo = pager
  let result: RoleResponseData = await reqAllRoleList(
    pageInfo.pageNo,
    pageInfo.limit,
    keyWord.value,
  )
  if (result.code == 200) {
    allRoleList.value = result.data.records
    pageInfo.total = result.data.total
  }
}
//搜索事件回调
const search = () => {
  getHasRole()
  keyWord.value = ''
}
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}
//添加职位回调
const addRole = () => {
  Object.assign(roleParams, {
    id: 0,
    roleName: '',
  })
  dialogVisite.value = true
  //清空上一次表单验证信息
  nextTick(() => {
    formRef.value.clearValidate('roleName')
  })
}
//编辑职位回调
const updateRole = (row: RoleData) => {
  dialogVisite.value = true
  Object.assign(roleParams, row)
  nextTick(() => {
    formRef.value.clearValidate('roleName')
  })
}
//添加职位确定
const saveRole = async () => {
  //验证表单结果,结果通过再发请求,结果未通过不发请求
  await formRef.value.validate()
  let result = await reqAddOrUpdateRole(roleParams)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `${roleParams.id ? '更新' : '添加'}成功!`,
    })
    dialogVisite.value = false
    getHasRole(roleParams.id ? pageInfo.pageNo : 1)
  } else {
    ElMessage({
      type: 'error',
      message: `${roleParams.id ? '更新' : '添加'}失败!`,
    })
  }
}
//取消
const cancel = () => {
  dialogVisite.value = false
}
//删除职位确定
const removeRole = async (row: RoleData) => {
  let result = await reqRemove(row.id as number)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除职位成功!',
    })
    getHasRole(
      allRoleList.value.length > 1 ? pageInfo.pageNo : pageInfo.pageNo - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除职位失败!',
    })
  }
}
//删除职位取消操作
const removeCancel = () => {
  ElMessage({
    type: 'error',
    message: '删除职位取消!',
  })
}
//分配权限按钮事件回调
const setPermisstion = async (row: RoleData) => {
  Object.assign(roleParams, row)
  drawer.value = true
  //根据职位获取权限数据
  let result: MenuResponseData = await reqAllMenuList(roleParams.id as number)
  if (result.code == 200) {
    menuListArr.value = result.data
    checkedArr.value = filterSclectArr(menuListArr.value, [])
  }
}
// checkedArr
const filterSclectArr = (allMenu: any, initArr: any) => {
  allMenu.forEach((item: any) => {
    if (item.children && item.children.length > 0) {
      //递归遍历
      filterSclectArr(item.children, initArr)
    }
    if (item.select && item.level == 4) {
      if (item.select) {
        initArr.push(item.id as number)
      }
    }
  })
  return initArr
}
//保存设置权限的事件回调
const save = async () => {
  //职位Id
  const roleId = roleParams.id
  //选中的节点ID数组
  let arr = tree.value.getCheckedKeys()
  //半选中的父节点的ID数组
  let arr2 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr2)
  let result = await reqSetPermission(roleId as number, permissionId)
  if (result.code == 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: '操作成功!',
    })
    //浏览器自动刷新一次
    window.location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败!',
    })
  }
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-form-item {
    display: flex;
    --font-size: 14px;
    margin-bottom: 0px;
  }
}
</style>
